# -*- coding: utf-8 -*-

"""
封装log方法

"""
import json
import logging
import os
import time
from logging import handlers

LEVELS = {
    'debug': logging.DEBUG,
    'info': logging.INFO,
    'warning': logging.WARNING,
    'error': logging.ERROR,
    'critical': logging.CRITICAL
}

appname = None
logger = logging.getLogger(appname)


# level = 'info'


def create_file(filename):
    path = filename[0:filename.rfind('/')]
    if not os.path.isdir(path):
        os.makedirs(path)
    if not os.path.isfile(filename):
        fd = open(filename, mode='w', encoding='utf-8')
        fd.close()
    else:
        pass


def get_current_time():
    return time.strftime(MyLog.date, time.localtime(time.time()))


class MyLog:
    config_path_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'config/config.json'))
    if not os.path.exists(config_path_dir):
        raise FileNotFoundError("请确保config配置文件存在！")
    with open(config_path_dir) as fb:
        loggingdata = json.load(fb)['logging']
    when = loggingdata['when']
    backupCount = loggingdata['backupCount']
    level = loggingdata['level']
    path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    log_file = path + '\\log\\log.log'
    err_file = path + '\\log\\err.log'
    logger.setLevel(LEVELS.get(level, logging.NOTSET))
    # create_file(log_file)
    # create_file(err_file)
    date = '%Y-%m-%d %H:%M:%S'
    # 设置日志输出格式
    logger = logging.getLogger()
    formatter = logging.Formatter('%(asctime)s -%(appname)s - %(message)s', date)
    # 创建Handler对象，StreamHandler：控制台输出，handler:全级别日志，err_handler:错误日志
    handler = handlers.TimedRotatingFileHandler(log_file, when=when, backupCount=int(backupCount))
    err_handler = handlers.TimedRotatingFileHandler(err_file, when=when, backupCount=int(backupCount))
    sh = logging.StreamHandler()

    # handler对象自定义日志级别
    handler.setLevel(logging.DEBUG)
    # handler对象自定义日志格式
    handler.setFormatter(formatter)

    # err_handler对象自定义日志级别
    err_handler.setLevel(logging.DEBUG)
    # err_handler对象自定义日志格式
    err_handler.setFormatter(formatter)

    # StreamHandler对象自定义日志级别
    sh.setLevel(logging.DEBUG)
    # StreamHandler对象自定义日志格式
    sh.setFormatter(formatter)

    logger.addHandler(err_handler)
    logger.addHandler(handler)
    logger.addHandler(sh)


if __name__ == "__main__":
    logger.info("123", extra={'appname': '自定义变量'})
